package com.fans.jwt.auth.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fans.common.constant.FansRspCon;
import com.fans.common.utils.FansResp;
import com.fans.common.utils.WriterUtil;

/**
 * 
 * @ClassName: SentinelUrlBlockHandler
 * @Description: sentinel自定义流控异常处理
 * @author fanhaohao
 * @date 2020年1月10日 下午5:00:20
 */
@Component
public class SentinelUrlBlockHandler implements UrlBlockHandler {

	@Override
	public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
		FansRspCon fansRspCon = FansRspCon.SUCCESS;
		// 不同的异常返回不同的提示语
		if (e instanceof FlowException) {// 接口限流了
			fansRspCon = FansRspCon.FLOWEXCEPTION;
		} else if (e instanceof DegradeException) {// 服务降级了
			fansRspCon = FansRspCon.DEGRADEEXCEPTION;
		} else if (e instanceof ParamFlowException) {// 热点参数限流了
			fansRspCon = FansRspCon.PARAMFLOWEXCEPTION;
		} else if (e instanceof SystemBlockException) {// 触发系统保护规则
			fansRspCon = FansRspCon.SYSTEMBLOCKEXCEPTION;
		} else if (e instanceof AuthorityException) {// 授权规则不通过
			fansRspCon = FansRspCon.AUTHORITYEXCEPTION;
		}
		WriterUtil.renderString(response, FansResp.error(fansRspCon));
	}
}

